﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using Common.Utilities.Excel;
using System.Text.RegularExpressions;
using Common.Utilities.Excel.Import;
using System.Data;
using ShareMarking.Service;
using ShareMarking.Entity;
using System.Configuration;
namespace ShareMarking.Web.admin.EnterPrise.Activity
{
    public partial class ordinaryimport : ManagePage
    {
        private static string diyhttp2 = ConfigurationManager.AppSettings["diyhttp2"];//本系统网站域名
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }

        #region 普通二维码导入信息==================================

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                #region 初始化变量
                //获取文件路径
                var filepath = Server.MapPath(this.txt_upload.Text.Trim());
                ExcelUtilities util = new ExcelUtilities();
                Excel excel = null;
                //获取配置
                var result = util.ImportExcel(filepath, "ordinaryimport", out excel);
                bool result2 = false;
                bool result3 = false;
                bool result4 = false;
                bool result5 = false;
                int SuccessCount = 0;//成功条数
                int ErrorCount = 0;//失败条数
                #endregion

                #region 循环判断添加数据
                if (result.Result == ExcelResultType.Succeed)
                {
                    
                    var datasource = excel.DataSet;
                    if (datasource.Tables.Count > 0)
                    {
                        foreach (DataRow row in datasource.Tables[0].Rows)
                        {
                            #region 循环判断更新或增加
                            if (!row[0].ToString().IsNullOrEmpty())
                            {
                                var qr_Activityentity = qr_ActivityService.Instance.Get_SingleEntity_byWhere(qr_Activity._.A_Name == row[0].ToString());
                                if (qr_Activityentity != null)//根据活动名称判断是否添加，有相同名称的活动，就叠加到失败条数
                                {
                                    #region  更新操作（不更新,只叠加错误条数）
                                    ComLib.LogLib.Log4NetBase.Log("有相同重复活动名称：" + qr_Activityentity.A_Name);
                                    ErrorCount += 1;//已经添加
                                    #endregion
                                }
                                else
                                {
                                    #region  增加操作 去掉数据源的空格和换行符

                                    #region 根据时间判断路径
                                    var currenturl = "";
                                    string diystr = "";
                                    DateTime ParStartTime_diy = Convert.ToDateTime(row.ItemArray[3].ToString().Trim());//.ToString("yyyy-MM-dd HH:mm:ss")
                                    DateTime ParEndTime_diy = Convert.ToDateTime(row.ItemArray[4].ToString().Trim());
                                    if (DateTime.Now < ParStartTime_diy)
                                    {
                                        currenturl = Regex.Replace(row.ItemArray[5].ToString().Trim(), @"\s", "");//去掉链接URL的空字符串//Par_Diy_wxbeforeUrl;
                                    }
                                    else if (DateTime.Now > ParStartTime_diy && DateTime.Now < ParEndTime_diy)
                                    {
                                        currenturl = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\s", "");//去掉链接URL的空字符串
                                    }
                                    else
                                    {
                                        currenturl = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\s", "");//去掉链接URL的空字符串
                                    }
                                    #endregion

                                    #region 获取Sceneid
                                    var sceneid = 0;
                                    qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1003);
                                    sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                                    #endregion

                                    #region 生成二维码方法
                                    diystr = diyhttp2 + "/a.aspx?c=" + sceneid.ToString();//（网站域名+访问页面+场景ID）
                                    var vigo = new ShareMarking.Interface.Qrcode_diy(diystr);
                                    resultdiy resultdiy = new resultdiy();
                                    var resultentity = ComLib.JsonHelper.JsonDeserialize<resultdiy>(vigo.GenerateQrCodeImg(diystr));
                                    #endregion

                                    #region 循环判断返回错误就重新请求
                                    while (resultentity.subcode == "01")
                                    {
                                        ComLib.LogLib.Log4NetBase.Log("错误信息:" + resultentity.msg + "/sceneid=" + sceneid);
                                        sceneid += 1;
                                        diystr = diyhttp2 + "/a.aspx?c=" + sceneid.ToString();
                                        resultentity = ComLib.JsonHelper.JsonDeserialize<resultdiy>(vigo.GenerateQrCodeImg(diystr));
                                    }
                                    #endregion

                                    if (resultentity.subcode == "00")
                                    {
                                        
                                        #region 保存二维码到数据库
                                        qr_DiyCode qrdiycode = new qr_DiyCode()
                                        {
                                            scene_id = sceneid.ToString(),
                                            type = 1003,
                                            code_url = diystr,//唯一短码
                                            source_url = currenturl,//跳转的真实url
                                            qrcode_url = diyhttp2 + resultentity.result,//二维码图片保存路径(网站域名+图片目录)
                                            isdelete = false,
                                            CreateOn = DateTime.Now,
                                        };
                                        result2 = qr_DiyCodeService.Instance.Add_Entity(qrdiycode);
                                        #endregion

                                        #region 保存活动
                                        var entity = new qr_Activity();
                                        entity.A_Name = Regex.Replace(row.ItemArray[0].ToString().Trim(), @"\r\n", "");
                                        entity.A_Manager = Regex.Replace(row.ItemArray[1].ToString().Trim(), @"\r\n", "");
                                        entity.A_Desc = Regex.Replace(row.ItemArray[2].ToString().Trim(), @"\r\n", "");
                                        entity.A_StartTime = ParStartTime_diy;
                                        entity.A_EndTime = ParEndTime_diy;

                                        entity.A_wxbeforeUrl = Regex.Replace(row.ItemArray[5].ToString().Trim(), @"\r\n", "");//活动前
                                        entity.A_wxUrl = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\r\n", "");//活动中                                      
                                        entity.A_wxafterUrl = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\r\n", "");//活动后
                                        entity.A_currentUrl = currenturl;//当前时间的currurl                                    
                                        entity.A_wxQrCodeID = qrdiycode.id.ToString();  
                                      
                                        entity.A_wxSceneID = qrdiycode.scene_id.ToString();
                                        entity.CreateOn = DateTime.Now;
                                        entity.isneedupdate = false;//                                   
                                        entity.isSenate = 0;//无参标识
                                        result3 = qr_ActivityService.Instance.Add_Entity(entity);
                                        #endregion

                                        #region 添加关联
                                        qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                                        {
                                            qr_Type = 1003,//1003是无参活动类型
                                            qr_CodeID = qrdiycode.id,//无参二维码id
                                            qr_Scene_ID = qrdiycode.scene_id,//场景值
                                            rel_Code = entity.ActivityID.ToString(),//无参活动ID
                                            IsDelete = false,
                                            CreateOn = DateTime.Now
                                        };
                                        result4 = qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                                        #endregion

                                        #region 更改二维码类型表
                                        type.QT_CurrentIndex = sceneid;//已使用的场景id
                                        type.QT_Used = type.QT_Used + 1;//已使用+1
                                        type.QT_Surplus = type.QT_Surplus - 1;//未使用-1
                                        result5 = qr_QrCodeTypeService.Instance.Update_Entity(type);
                                        #endregion
                                    }
                                    if (result2 && result3 && result4 && result5)
                                    {
                                        SuccessCount += 1;
                                    }
                                    else
                                    {
                                        ErrorCount += 1;//已经添加
                                    }
                                    #endregion
                                }
                            }
                            else
                            {
                                ErrorCount += 1;//失败条数
                            }
                            #endregion
                        }
                    }
                    JscriptMsg("导入成功" + SuccessCount + "条，失败" + ErrorCount + "条！", "List.aspx?isSenate=false", "Success");
                }
                else
                {
                    JscriptMsg("ordinaryimport", "导入失败！请检查excel！", "", "Error");
                }
                #endregion
            }
            catch (Exception ex)
            {
                AddAdminLog(DTEnums.ActionEnum.Import.ToString(), "导入qr_Activity出错 错误为" + ex.Message + "");
                JscriptMsg("导入添加数据失败！请联系管理员！", "List.aspx?isSenate=false", "Error");
            }
        }
        #endregion
    }
}